package com.java.learning.demo.config;

import com.java.learning.demo.common.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;
import java.util.List;

@ControllerAdvice
@ResponseBody
@Slf4j
public class ControllerExceptionHandler {

    /**
     * 参数验证异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler({ConstraintViolationException.class})
    public ResultData<Object> parameterExceptionHandler(ConstraintViolationException e) {
        log.error("[parameterExceptionHandler]" + e.getMessage(), e);
        return ResultData.newInstance(9, "参数校验错误");
    }

    /**
     * 参数验证异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultData<Object> parameterExceptionHandler(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        //多个错误，取第一个
        FieldError error = fieldErrors.get(0);
        String msg = error.getDefaultMessage();
        return ResultData.newInstance(10, "方法参数错误:"+msg);
    }

    @ExceptionHandler({IllegalArgumentException.class})
    public ResultData<Object> illegalArgumentException(IllegalArgumentException e) {
        log.error("[illegalArgumentException]" + e.getMessage(), e);
        return ResultData.newInstance(11, "非法参数错误");
    }

    @ExceptionHandler({MissingServletRequestParameterException.class})
    public ResultData<Object> missParameterException(MissingServletRequestParameterException e) {
        String msg = ("缺少参数  name:" + e.getParameterName() + ", type:" + e.getParameterType());
        log.error("[missParameterException]" + msg);
        return ResultData.newInstance(12, msg);
    }

    /**
     * 其它异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    public ResultData<Object> exceptionHandler(Exception e) {
        log.error("[exceptionHandler]" + e.getMessage(), e);
        return ResultData.newInstance(-1, "系统服务优化中...");
    }
}
